# algorithm/models/tag_values.py
from django.db import models
from django.contrib.auth.models import User
from ..utils import mastery_level1, diff_score
from users.models import User as CustomUser  # 自定义的User表
from tag.models import AlgorithmTag
from problems.models import Problem
import logging
logger = logging.getLogger('algorithm')

# 标签总分模型
class TagValue(models.Model):
    tag = models.ForeignKey(AlgorithmTag, on_delete=models.CASCADE, to_field='index', db_column='tag_index',primary_key=True)
    tag_value = models.FloatField(default=0.0)

    def __str__(self):
        return f"Tag {self.tag.index}: {self.tag_value}"

    # 使用类中静态方法创建
    @classmethod
    def create_or_update_tag_value(cls, tag_index):
        try:
            tag_value = cls.calculate_tag_value(tag_index)
            tag = AlgorithmTag.objects.get(index=tag_index)
            tag_value_obj, created = cls.objects.update_or_create(
                tag=tag,
                defaults={'tag_value': tag_value}
            )
            logger.info(f"{cls.__name__}.create_or_update_tag_value {tag_value} Success")
            return tag_value_obj, created
        except AlgorithmTag.DoesNotExist:
            print(f"Tag with index {tag_index} does not exist.")
            logger.error(f"{cls.__name__}.create_or_update_tag_value : tag {tag_index} does not exist.")
            return None, False

    @classmethod
    def calculate_tag_value(cls, tag_index):
        try:
            tag = AlgorithmTag.objects.get(index=tag_index)
            # 难度分数映射
            total_value = 0.0

            # 获取这个标签关联的所有题目
            problems = tag.problems.all()

            # 遍历每个题目，计算其分数并累加到总分
            for problem in problems:
                # 仅统计属于 AlgorithmTag 的标签
                algorithm_tags_count = problem.tags.filter(index__in=AlgorithmTag.objects.values_list('index', flat=True)).count()

                if problem.difficulty_index is not None and problem.difficulty_index < len(diff_score):
                    if algorithm_tags_count > 0:  # 确保有算法标签才进行计算
                        score = diff_score[problem.difficulty_index] / algorithm_tags_count
                        total_value += score
            logger.info(f"{cls.__name__}.calculate_tag_value tag {tag_index} Success")
            return total_value
        except AlgorithmTag.DoesNotExist:
            logger.error(f"{cls.__name__}.calculate_tag_value : tag {tag_index} does not exist.")
            print(f"Tag with index {tag_index} does not exist.")
            return None

    @classmethod
    def create_all_tag_value(cls):
        # 遍历所有的算法标签
        for tag in AlgorithmTag.objects.all():  # 使用 AlgorithmTag 代替 Tag
            # 直接调用 TagValue 类中的方法来创建或更新 TagValue
            tag_value_obj, created = TagValue.create_or_update_tag_value(tag.index)
            # 返回值 created 为 True 表示发生创建，为 False 表示是更新
            # 检查返回的对象是否有效，并打印相应的结果
            if tag_value_obj is not None:
                print(f'Successfully {"created" if created else "updated"} TagValue for tag {tag.index}')
            else:
                print(f"Failed to create or update TagValue for tag {tag.index}")
        logger.info(f"{cls.__name__}.create_all_tag_value Success")
    @classmethod
    def clear_all_tag_value(cls):
        cls.objects.all().delete()  # 删除所有 TagValue 实例
        print("All TagValue records have been cleared.")
        logger.info(f"{cls.__name__}.clear_all_tag_value Success")